from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.events import EVENT_JOB_ERROR, JobExecutionEvent
from utils.common.logger import log


class TaskScheduler:
    '''
    封装了APScheduler类，可选阻塞式定时任务或后台服务式
    '''

    def __init__(self, background=False):
        self.scheduler = BackgroundScheduler() if background else BlockingScheduler()
        self.scheduler.add_listener(self.mylistener, EVENT_JOB_ERROR)
        self.scheduler._logger = log.logger

    def __del__(self):
        self.scheduler.remove_all_jobs()
        if self.scheduler.running:
            self.stop()

    def mylistener(self, event: JobExecutionEvent):
        log.logger.error(
            f"{event.exception} ouccurred in {event.job_id}...")
        self.scheduler.remove_job(event.job_id)

    def get_job(self, job_id: str):
        return self.scheduler.get_job(job_id)

    def get_jobs(self):
        return self.scheduler.get_jobs()

    def new_job(self, func, trigger="interval", seconds=0, minutes=0, hours=0, days=0, next_run_time=datetime.now(), id=""):
        '''
        添加新任务到规划器，默认1s执行一次，立即执行
        '''
        if self.get_job(id) is None:
            self.scheduler.add_job(
                func=func, trigger=trigger, seconds=seconds,
                minutes=minutes, hours=hours, days=days,
                next_run_time=next_run_time, id=id)
            return True

        return False

    def run(self):
        self.scheduler.start()

    def pause(self):
        self.scheduler.pause()

    def resume(self):
        self.scheduler.resume()

    def stop(self):
        self.scheduler.remove_all_jobs()
        self.scheduler.shutdown(wait=False)
